﻿using Furion.FriendlyException;
using Gear.Core.ErrorControl;
using Gear.ToolKits.Helper;
using Gear.Web.Api.DynamicDataApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gear.Web.Api.DynamicDataApi.Macro
{
    /// <summary>
    /// 排序条件宏
    /// </summary>
    public static class SequenceMacro
    {
        private static readonly string Sortword = "sorting";// 查询标识关键字

        /// <summary>
        /// 排序条件匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string SequenceTrans(string _content, Dictionary<string, object> param)
        {
            StringBuilder sb = new(_content);

            param.TryGetValue(Sortword, out object Value); if (Value == null) return _content;

            var SortMod = JsonHelper.DeserializeJSON<Sorts>(Value.ToString());

            if (SortMod != null && SortMod.SortKey.Count > 0)
            {
                // 验证查询关键字是否是源数据字段
                CheckIsDataKey(SortMod);
                switch((SortOrderType)SortMod.SortOrder)
                {
                    case SortOrderType.ASC:
                        sb.Append($" order by {GetListValue(SortMod.SortKey)} asc");
                        break;
                    case SortOrderType.DESC:
                        sb.Append($" order by {GetListValue(SortMod.SortKey)} desc");
                        break;
                    default:
                        sb.Append($" order by {GetListValue(SortMod.SortKey)} asc");
                        break;
                }
            }

            return sb.ToString();
        }

        #region == ToolKits ==
        private static string GetListValue(List<string> list)
        {
            StringBuilder sb = new();
            int i = 0;
            list.ForEach(x => {
                if (i == 0) sb.Append($"{x}");
                else sb.Append($",{x}");
                i++;
            });

            return sb.ToString();
        }

        private static void CheckIsDataKey(Sorts Sorts)
        {
            Sorts.SortKey.ForEach(x => {
                var key = x;
                if (false) throw Oops.Oh(ErrorCodeModel.E1200_4_2, key);
            });

        }
        #endregion
    }
}
